package com.pitaya.winwine.service;

import java.util.Date;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pitaya.framework.common.StringUtils;
import com.pitaya.winwine.domain.Tag;
import com.pitaya.winwine.domain.Topic;
import com.pitaya.winwine.repository.TopicRepository;

@Service
public class TopicService {
	
	@Autowired
	private TopicRepository topicRepository;

	@Transactional
	public void save(Topic topic) {
		if(topic.getId() == null) {
			topic.setClickCount(0);
			topic.setCommentCount(0);
		}else {
			topic = topicRepository.findOne(topic.getId());
		}
		initContent(topic);
		saveTags(topic);
		topicRepository.save(topic);
	}
	
	private void initContent(Topic topic) {
	    String content = topic.getContent();
	    if(StringUtils.isNotBlank(content)) {
	    	Document doc = Jsoup.parse(content);
	    	Element firstImage = doc.select("img").first();
	    	if(firstImage != null) {
	    		topic.setImageUrl(firstImage.attr("src"));
	    	}
	    	String text = doc.text();
	    	if(StringUtils.isNotBlank(text)) {
	    		topic.setSummary(text.substring(0, Math.min(text.length(), 100)));
	    	}
	    }
	    topic.setEditTime(new Date());
	}
	private void saveTags(Topic topic) {
	    if (StringUtils.isNotBlank(topic.getTagStr())) {
	    	topic.getTags().clear();
	    	for(String tag : topic.getTagStr().split(";")) {
	    		topic.addTag(new Tag(Integer.parseInt(tag.split(":")[0])));
	    	}
	    }
	}
}
